package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    //新增地址
    @Override
    public void add(AddressBook addressBook) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //并不将新增的地址设为默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    //查询当前登录用户的所有地址
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);

    }

    //设置默认地址并不是简单的将该地址设置为默认地址 因为默认地址一般只有一个 所以我们第一步要将所有地址都设置为非默认地址 第二步再根据id设置该地址为默认地址
    @Override
    public void setDefault(AddressBook addressBook) {
        //分两步 第一步将给用户的所有的地址都设置为非默认地址
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);
        //第二步再根据id设置该地址为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }


    //根据id查询指定地址
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    //修改地址

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    //删除地址
    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }
}
